package cn.tju.leavingsystem.web;

import cn.tju.leavingsystem.entity.Staff;
import cn.tju.leavingsystem.service.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/staff")
public class StaffController {
    @Autowired
    private StaffService staffService;

    @GetMapping("/")
    private Map<String, Object> listStaff(){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        List<Staff> list = staffService.getStaffList();
        modelMap.put("error_code", 0);
        modelMap.put("message", "Success requesting data");
        modelMap.put("data", list);
        return modelMap;
    }

    @GetMapping("/{staffId}")
        private Map<String, Object> getStaffById(@PathVariable Integer staffId){
            Map<String, Object> modelMap = new HashMap<String, Object>();
            Staff staff = staffService.getStaffById(staffId);
            if(staff != null){
                modelMap.put("error_code", 0);
                modelMap.put("message", "Success requesting data");
            }else {
                //数据库中没有该staffId
                modelMap.put("error_code", 1);
                modelMap.put("message", "Coundn't find data about staff, check whether your staffId is valid");
            }
            modelMap.put("data", staff);
            return modelMap;
    }

    @PostMapping("/")
    private Map<String, Object> addStaff(@ModelAttribute Staff staff){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        boolean success = staffService.addStaff(staff);
        if(success){
            modelMap.put("error_code", 0);
            modelMap.put("message", "Success inserting staff");
        }else{
            modelMap.put("error_code", -1);
            modelMap.put("message", "Fail to insert staff");
        }
        return modelMap;
    }

    @PutMapping("/{staffId:\\d+}")
    private Map<String, Object> updateSatff(@ModelAttribute Staff staff){
        Map<String, Object> modelMap = new HashMap<String, Object>();
        if(staffService.modifyStaff(staff)){
            modelMap.put("error_code", 0);
            modelMap.put("message", "Success updating staff");
        }else{
            modelMap.put("error_code", -1);
            modelMap.put("message", "Fail to update staff");
        }
        return modelMap;
    }

}
